import service from '@/utils/request'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/ruoyi'

const baseURL = import.meta.env.VITE_APP_BASE_API

// 检测 Tauri 环境
const isTauri = typeof window !== 'undefined' && (
  window.__TAURI__ !== undefined ||
  window.__TAURI_INTERNALS__ !== undefined ||
  window.location.protocol === 'tauri:'
)

// Tauri 环境下的文件保存函数
let tauriSaveFile = null
if (isTauri) {
  Promise.all([
    import('@tauri-apps/plugin-dialog'),
    import('@tauri-apps/plugin-fs')
  ]).then(([dialogModule, fsModule]) => {
    tauriSaveFile = async (blob, defaultName) => {
      try {
        // 打开保存文件对话框
        const filePath = await dialogModule.save({
          defaultPath: defaultName,
          filters: [{
            name: 'All Files',
            extensions: ['*']
          }]
        })

        if (filePath) {
          // 将 Blob 转换为 ArrayBuffer
          const arrayBuffer = await blob.arrayBuffer()
          const uint8Array = new Uint8Array(arrayBuffer)

          // 写入文件
          await fsModule.writeFile(filePath, uint8Array)
          ElMessage.success('文件已保存到: ' + filePath)
        }
      } catch (error) {
        console.error('Tauri 文件保存失败:', error)
        ElMessage.error('文件保存失败: ' + error.message)
      }
    }
  }).catch(err => {
    console.error('加载 Tauri 文件插件失败:', err)
  })
}

export default {
  name(name, isDelete = true) {
    var url = baseURL + "/common/download?fileName=" + encodeURIComponent(name) + "&delete=" + isDelete
    service({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  resource(resource) {
    var url = baseURL + "/common/download/resource?resource=" + encodeURIComponent(resource);
    service({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  zip(url, name) {
    var url = baseURL + url
    service({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' })
        this.saveAs(blob, name)
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  async saveAs(blob, name, opts) {
    // Tauri 环境使用原生文件对话框
    if (isTauri && tauriSaveFile) {
      await tauriSaveFile(blob, name)
    } else {
      // 浏览器环境使用 file-saver
      saveAs(blob, name, opts)
    }
  },
  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
  }
}

